package com.blog.base.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;







import com.blog.admin.bean.User;
import com.blog.base.validator.InspectorException;


/**
 * @todo BaseController
 * @author fg
 * @date 2016年1月7日
 */
@Controller
public class BaseController
{
	protected ModelAndView mav = new ModelAndView();
	
	protected JSONObject json = new JSONObject();
	
	protected Integer success;
	
	protected String msg;
	
	protected final String DEFULT_PASSWORD ="blog123456";
	
	
	/**
	 * @todo 将request的参数封装给map 并直接获取
	 * @author fg
	 * @date 2016年4月6日
	 */
	protected Map<String,String> getRequestMap()
	{
		HttpServletRequest request = this.getHttpRequest();
		Map<String,String> map = new HashMap<String, String>();
		if("1".equals(request.getParameter("isMap")))
		{
			Enumeration<String> pNames = request.getParameterNames();
			while(pNames.hasMoreElements()){
			    String name=(String)pNames.nextElement();
			    String value=request.getParameter(name);
			    if("pageSize".equals(name)||"pageNum".equals(value)||"pageNum".equals("isMap"))
			    	continue;
			    
			    if(StringUtils.isBlank(name)||StringUtils.isBlank(value))
			    	continue;
			    
			    map.put(name, value);
			    
			}
		}
		return map;

	} 
	

	
    /**
     * @todo 公共的异常处理类
     * @author fg
     * @date 2016年1月25日
     */
    @ExceptionHandler(Exception.class)  
    public ModelAndView operateExp(Exception e,HttpServletRequest request){  
        //ExceptionHandler处理异常时，Model，是不能用的，否则会不起作用，这里用了HttpServletRequest  
    	String message = e.toString();  
        if (message.lastIndexOf(":") != -1)  
         message = message.substring(0, message.lastIndexOf(":")); 
        System.out.println(message);
        mav.addObject("err", getTraceInfo(e).append(message).toString());
        mav.setViewName("common/error_page");
        //request.setAttribute("err", ex.getMessage());  
        return mav;  
    }  
    
    /**
     * @todo 异常处理类（授权）
     * @author fg
     * @date 2016年3月15日
     */
    @ExceptionHandler({UnauthorizedException.class})  
    public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {  
    	String message = e.toString();  
        if (message.lastIndexOf(":") != -1)  
         message = message.substring(0, message.lastIndexOf(":")); 
        mav.addObject("err", "无权访问");
        mav.setViewName("common/error_page");
        return mav;  
    }
    /**
     * @todo 公共抛出后台校验异常的方法
     * @author fg
     * @throws InspectorException 
     * @date 2016年4月6日
     */
	protected void throwInspectorException(BindingResult result) throws InspectorException{
        StringBuffer sb = new StringBuffer("<br/>");
        System.out.println(result);
        for(FieldError fieldError :result.getFieldErrors()){
        	//errorMessage=err.get(i).getDefaultMessage();//得到错误消息
            sb.append("错误字段："+fieldError.getField()+"<br/>"+" 值 ：" +fieldError.getRejectedValue()+"<br/>");
        }
        throw new InspectorException(sb+"");
	}

	
    /**
     * @todo 后台校验异常捕获
     * @author fg
     * @date 2016年4月6日
     */
    @ExceptionHandler(InspectorException.class)  
    public ModelAndView inspector(InspectorException e,HttpServletRequest request){ 
    	ModelAndView mav = new ModelAndView();
    	mav.setViewName("common/error_page");
    	mav.addObject("err","<br/>后台校验出现错误："+e.getMessage());
    	
		return mav;
    } 
    
	/**
	 * @todo 获取当前用户
	 * @author fg
	 * @date 2016年4月11日
	 */
	public User getCurUser() {
		return (User) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
	}
    
    public static StringBuffer getTraceInfo(Exception e) {  
    	  StringBuffer sb = new StringBuffer();  
    	  StackTraceElement[] stacks = e.getStackTrace();  
    	  for (int i = 0; i < stacks.length; i++) {  
    	    sb.append("类: ")
    	      .append(stacks[i].getClassName())  
    	      .append("; <br/>方法: ")
    	      .append(stacks[i].getMethodName())  
    	      .append("; <br/>行数: ")
    	      .append(stacks[i].getLineNumber())  
    	      .append("; <br/>异常: ");  
    	  }  
    	  return sb;  
	 } 
    

	/**
	 * @todo getParameter
	 * @author fg
	 * @date 2016年4月12日
	 */
	public String getParameter(String key)
	{
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request.getParameter(key);
	}


	/**
	 * @todo getHttpRequest
	 * @author fg
	 * @date 2016年4月12日
	 */
	public static HttpServletRequest getHttpRequest()
	{
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
}
